using UnityEngine;

[ExecuteAlways]
[RequireComponent(typeof(Camera))]
public class OrthoCameraController : MonoBehaviour
{
    public enum FitMode
    {
        Native,     // Unity 原生处理
        LockHeight, // 锁定高度
        LockWidth,  // 锁定宽度
        LockBoth    // 同时锁定宽度 & 高度（letterbox/pillarbox）
    }

    [Header("显示模式")]
    public FitMode fitMode = FitMode.LockWidth;

    [Header("参考分辨率（像素）")]
    public float referenceWidth  = 1920f;
    public float referenceHeight = 1080f;

    [Header("精灵像素／单位 (Sprite PPU)")]
    public float pixelsPerUnit   = 100f;

    private Camera cam;
    private int lastW = 0, lastH = 0;

    void Awake()
    {
        cam = GetComponent<Camera>();
        ApplySettings();
    }

    void Update()
    {
        // 仅当分辨率变化时才重新计算
        if (Screen.width != lastW || Screen.height != lastH)
            ApplySettings();
    }

    void OnValidate()
    {
        if (cam == null) cam = GetComponent<Camera>();
        ApplySettings();
    }

    private void ApplySettings()
    {
        lastW = Screen.width;
        lastH = Screen.height;

        // 恢复全屏显示 (必要时会在 LockBoth 下被覆盖)
        cam.rect = new Rect(0, 0, 1, 1);

        float screenAspect = (float)Screen.width / Screen.height;
        float targetAspect = referenceWidth / referenceHeight;

        switch (fitMode)
        {
            case FitMode.Native:
                // Unity 默认 orthographicSize，不做处理
                break;

            case FitMode.LockHeight:
                // 固定高度：orthographicSize = (worldHeight / 2)
                cam.orthographicSize = (referenceHeight / pixelsPerUnit) * 0.5f;
                break;

            case FitMode.LockWidth:
                // 固定宽度：worldWidth = referenceWidth / PPU
                // orthographicSize = worldWidth / (2 * aspect)
                float worldW = referenceWidth / pixelsPerUnit;
                cam.orthographicSize = worldW / (2f * screenAspect);
                break;

            case FitMode.LockBoth:
                // 同时锁定：先做 letterbox/pillarbox，再固定高度
                if (screenAspect >= targetAspect)
                {
                    // 屏幕更“宽”，左右留黑
                    float scaleW = targetAspect / screenAspect;
                    cam.rect = new Rect((1f - scaleW) / 2f, 0, scaleW, 1f);
                }
                else
                {
                    // 屏幕更“高”，上下留黑
                    float scaleH = screenAspect / targetAspect;
                    cam.rect = new Rect(0, (1f - scaleH) / 2f, 1f, scaleH);
                }
                cam.orthographicSize = (referenceHeight / pixelsPerUnit) * 0.5f;
                break;
        }
    }
}